package main;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class FileUtil {

	File srcFile = new File("default.json");
	BufferedReader in;
	PrintWriter out;
	private String myself;
	
	public void setMyself(String myself) {
		this.myself = myself;
	}

	/**
	 * checks if specified user exists
	 * 
	 * @param nameToCheck
	 * @return unparsed line with username and address
	 */
	public synchronized String findRecordLine(String nameToCheck) {
		String text = "";
		try {
			in = new BufferedReader(new FileReader(srcFile));
			while (in.ready()) {
				text = in.readLine();
				if (text.startsWith("[\"")) {
					String[] name = text.split("\"", 3); // name[0] all before
															// first match,
															// name[1]
															// everything
															// between first and
															// second match,
															// name[2] remaining
															// string
					if (name[1].equalsIgnoreCase(nameToCheck)) {
						return text;
					}
				}
				// System.out.println(text);
			}
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		finally{
			try {
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return "Not found";
	}

	/**
	 * @param record
	 *            unparsed json line
	 * @return array {name, IP:port}
	 */
	public String[] parseRecord(String record) {
		String[] name = record.split("\"", 3); // name[0] all before first
												// match, name[1] everything
												// between first and second
												// match, name[2] remaining
												// string
		String[] adress = name[2].split("\"");
		return new String[] { name[1], adress[1] };
	}

	/**
	 * @return list of lines
	 */
	public synchronized List<String> getLines() {

		List<String> lines = new ArrayList<String>();
		try {
			in = new BufferedReader(new FileReader(srcFile));

			while (in.ready()) {
				String line = in.readLine();
				if (line.startsWith("[\"")) {
					String[] name = line.split("\"", 3);
					lines.add(line);
				}
			}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally{
			try {
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return lines;
	}

	/**
	 * appends given line into a file
	 * 
	 * @param newLine
	 *            //raw (unparsed) record from json file line to append
	 * @return false if line is already in the file
	 */
	public synchronized boolean appendLine(String newLine) {
		String[] name = this.parseRecord(newLine);
		if (!this.findRecordLine(name[0]).equals("Not found")) {
			return false;// line already is in the file.
		}
		if(myself!=null && newLine.startsWith(this.myself)){
			return false;
		}
		File tempFile = new File("tempFile.json");
		Scanner scanner = null;
		try {
			scanner = new Scanner(srcFile);
			// in = new BufferedReader(new FileReader(srcFile));
			out = new PrintWriter(new BufferedWriter(new FileWriter(tempFile)));
			String line;
			while (scanner.hasNext()) {
				line = scanner.nextLine();
				if (line.endsWith("\"]")) { // dobavit' zapatuju v pred
											// posledniju zapis'
					out.println(line + ",");
				} else if (line.equals("]")) { // last line in the original file
					out.println(newLine);
					out.println("]");
					break; // should stop here
				} else { // all other lines
					out.println(line);
				}
			}

			// Reshenie #1 na bug s failami: Pozvat' System.gc(); , i sdelat'
			// dva while(true) kotorye budut pytats'ja
			// udalit' i potom pereimenovat' fajly poka ne poluchits'ja.
			// Bez System.gc(); budet beskonechnyj cikl.

			// in.close();
			// out.close();
			// System.gc();// to avoid bug
			// //TODO STILL first line is ignored.
			//
			// while(true){
			// if(this.srcFile.delete()==false){
			// continue;
			// }
			// else{
			// break;
			// }
			// }
			// while(true){
			// if(tempFile.renameTo(this.srcFile)==false){
			// continue;
			// }
			// else{
			// break;
			// }
			// }

			// System.out.println("Old file deleted and new one renamed:");//remove
			// later
			// System.out.println(this.srcFile.delete());
			// System.out.println(tempFile.renameTo(this.srcFile));
			// tempFile.delete();
			// this.srcFile = new File("default.json");
			// TODO DO NOT APPEND MYSELF. OR ADD AUTOMATIC NAME SELECTION ON
			// START.

		} catch (IOException e) {
			e.printStackTrace();
		} finally { // Reshenie #2 na bug s failami: zakrytj in & out v finally,
					// no pozvat' System.gc(); vse ravno nado,
			scanner.close();
			scanner = null;
			out.close();
			out = null;
//			System.gc();
		}

		System.out.println("Old file deleted and new one renamed:");// remove
																	// later
		System.out.println(this.srcFile.delete());
		System.out.println(tempFile.renameTo(this.srcFile));
		tempFile.delete();
		this.srcFile = new File("default.json");
		// TODO DO NOT APPEND MYSELF. OR ADD AUTOMATIC NAME SELECTION ON START.

		return true;
	}
}
